<?php
/**
 * Sms.php
 * 短信相关类
 * 
 * @author  王中艺 <wangzy_smile@qq.com>
 * @date    2018-06-30 15:02:54
 */

namespace App\Utils;
use App\Exceptions\NormalException;
use Illuminate\Support\Facades\Cache;

abstract class Sms {

    private static $drivers = [];

    /**
     * 验证码发送
     * @param   $mobile 手机号
     * @return  boolean
     */
    function sendCode($mobile){
        if(!Format::isMobile($mobile)){
            throw new NormalException(604, 'mobile');
        }

        //锁检查
        if($this->isLock($mobile)){
            throw new NormalException(613);
        }

        //执行发送
        $code = $this->createCode($mobile);
        $codeText = $this->createCodeText($code);
        if($this->toSend($mobile, $codeText)){
            //日志添加
            Log::getInstance('file')->put('send_sms', [
                'mobile' => $mobile,
                'content' => $codeText
            ]);
            //加锁
            $this->addLock($mobile);
        }

        return true;
    }

    /**
     * 发送
     * @param   $mobile
     * @return  boolean
     */
    abstract protected function toSend($mobile, $content);

    /**
     * 单例获取
     * @param   $driver [<description>]
     * @return  instance [<description>]
     */
    static function getInstance($driver = null){
        //驱动获取
        $driver = $driver ? $driver : config('sms.driver');

        //单例检测
        if(!isset(self::$drivers[$driver])){
            switch($driver){
                case 'yunsms':
                    self::$drivers[$driver] = new \App\Utils\Sms\YunSms();
                break;
                default:
                    throw new NormalException(610);
                break;
            }
        }

        return self::$drivers[$driver];
    }

    /**
     * 短信码验证
     * @param   $mobile 手机号
     * @param   $code 验证码
     * @return  boolean [<description>]
     */
    function verifyCode($mobile, $code){
        if(\App::environment('local')){
            return true;
        }

        $rightCode = Cache::get('sms_code_'.$mobile);
        if(!$rightCode){
            return false;
        }

        return $rightCode == $code;
    }

    /**
     * 生成短信验证码
     * @param   $mobile 手机号
     * @return  $code
     */
    function createCode($mobile){
        $code = rand(111111, 999999);

        //缓存记录
        Cache::put('sms_code_'.$mobile, $code, 20);

        return $code;
    }

    /**
     * 生成短信验证码内容
     * @param   $code
     * @return  text [<description>]
     */
    function createCodeText($code){
        return '你好，您的验证码为：'.$code.'【应答网络】';
    }

    /**
     * 加锁
     * @param   $mobile
     * @return  boolean [<description>]
     */
    function addLock($mobile){
        Cache::put('sms_lock_'.$mobile, '1', 0.5);
        return true;
    }

    /**
     * 检查锁
     * @param   $mobile 手机号
     * @return  boolean [<description>]
     */
    function isLock($mobile){
        return Cache::get('sms_lock_'.$mobile) ? true : false;
    }
}
